package com.example.shushiyunsst.fragment.sigin

import android.os.Bundle
import android.text.Editable
import android.view.View
import android.widget.Toast
import com.alibaba.fastjson.JSON
import com.example.library_common.base.BaseDataBindingFragment
import com.example.library_common.constant.CLICK_BLE
import com.example.library_common.networking.RestClient
import com.example.library_common.utils.OnTextListener
import com.example.shushiyunsst.MainActivity
import com.example.shushiyunsst.R
import com.example.shushiyunsst.databinding.SignUpFragmentLayoutBinding
import com.example.shushiyunsst.widget.verification.new_view.NewVerificationListener
import com.example.shushiyunsst.widget.verification.new_view.VerificationViewBean
import com.example.shushiyunsst.widget.verification.view.VerificationListener.SUCCESS_STATUS
import com.example.wallet.bean.UserInfoWrapper
import com.example.wallet.constant.REGEX_EMAIL
import com.example.wallet.constant.REGEX_PASSWORD_NUMBER_AND_LETTER
import com.example.wallet.db.UserInfoManager
import com.example.wallet.global.AppGlobals
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.core.BasePopupView
import com.lxj.xpopup.interfaces.SimpleCallback
import kotlinx.android.synthetic.main.add_paying_way_pop.*
import java.util.regex.Pattern

/**
 * 注册
 * */
class SignUpFragment : BaseDataBindingFragment<SignUpFragmentLayoutBinding>(), LabInfo,
    View.OnClickListener,
    OnTextListener {

    override fun labTitle(): String {
        return "注册"
    }

    companion object {
        fun newInstance(): SignUpFragment {
            val args = Bundle()
            val fragment = SignUpFragment()
            fragment.arguments = args
            return fragment
        }
    }

    private var signUpPhone = ""

    private var signUpPassWord = ""

    private var signUpPayingPassWord = ""

    //（测试8个8）
    private var signUpInvitedCoding = ""

    private var signUpEmail = ""

    private var signPageListener: SignPageListener? = null

    fun setSignPageListener(signPageListener: SignPageListener?): SignUpFragment {
        this.signPageListener = signPageListener
        return this
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mSuperBackPressedSupport=false
    }


    override fun layoutId() = R.layout.sign_up_fragment_layout

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        viewBinder.onViewClick = this
        viewBinder.onTextListener = this

        viewBinder.signUpEMail.addExMethod({ validatorForEMail() })

        viewBinder.signUpPassWord.addExMethod({
            validatorPassWordSameCode()
            validatorPassWordNumbersAndLetter()
        })

        viewBinder.signUpPayingPassWord.addExMethod({
            validatorPayingPassWordNumbersAndLetter()
            validatorPayingPassWordSameCode()
        })
    }

    private fun validatorPayingPassWordSameCode() = passWordSameCode(signUpPayingPassWord)

    private fun validatorPayingPassWordNumbersAndLetter() =
        passWordNumbersAndLetter(signUpPayingPassWord)


    private fun validatorPassWordNumbersAndLetter() = passWordNumbersAndLetter(signUpPassWord)

    private fun validatorPassWordSameCode() = passWordSameCode(signUpPassWord)


    //验证密码是否为数字与字母组合
    private fun passWordNumbersAndLetter(test: String): String {
        var res = ""
        if (test.isEmpty()) return res

        val p = Pattern.compile(REGEX_PASSWORD_NUMBER_AND_LETTER)

        val matcher = p.matcher(test)

        if (!matcher.matches()) {
            res = _mActivity.getString(R.string.password_by_num_and_letter)
        }
        return res
    }


    //验证密码不能为同一数字
    private fun passWordSameCode(test: String): String {
        var res = ""

        if (test.isEmpty()) return res

        val toCharArray = test.toCharArray()

        var sameCount = 0

        val firstChar = toCharArray[0]

        toCharArray.forEach {

            if (firstChar == it) {

                sameCount++

            }
        }
        if (sameCount == signUpPassWord.length) {

            res = _mActivity.getString(R.string.password_same_code_0)

        }
        return res
    }

    //验证邮箱格式
    private fun validatorForEMail(): String {
        var res = ""

        if (signUpEmail.isEmpty()) return res

        val p = Pattern.compile(REGEX_EMAIL)
        val matcher = p.matcher(signUpEmail)

        if (!matcher.matches()) {
            res = _mActivity.getString(R.string.email_not_validate)
        }
        return res
    }

    override fun onClick(p0: View?) {
        when (p0?.id) {
            R.id.sign_up_tv -> {
                //立即验证
                if (!checkInfo()) return

                if (!CLICK_BLE) return

                CLICK_BLE = false
                val newInstance = SignUpVerifyFragment(_mActivity)
                newInstance.setVerificationListener(object : NewVerificationListener {
                    override fun notifyStatusResult(status: Int) {
                        when (status) {
                            SUCCESS_STATUS -> {
//                                dismiss
                                newInstance.dismiss()
                                registerAccount(newInstance.getVerificationViewBean())
                            }
                        }
                    }

                })
                XPopup.Builder(_mActivity)
                    .hasShadowBg(false)
                    .setPopupCallback(object : SimpleCallback(){
                        override fun onDismiss(popupView: BasePopupView?) {
                            super.onDismiss(popupView)
                            CLICK_BLE = true
                        }
                    })
                    .asCustom(newInstance)
                    .show()

//                val newInstance = SignUpVerifyFragment.newInstance()
//
//                newInstance.setVerificationListener(object : NewVerificationListener {
//                    override fun notifyStatusResult(status: Int) {
//                        when (status) {
//                            SUCCESS_STATUS -> {
//                                newInstance.pop()
//                                registerAccount(newInstance.getVerificationViewBean())
//                            }
//                        }
//                    }
//
//                })
//                ShUtils.startFragmentDoNotHideSelf(this@SignUpFragment, newInstance)
            }
            R.id.sign_in_now -> {
                //立即登录
                signPageListener?.intoSignIn()
//                val maps = mapOf(
//                    "account" to signUpPhone,
//                    "password" to signUpPassWord
//                )

//                RestClient.builder()
//                    .url(R.string.appLogin)
//                    .raw(JSON.toJSONString(maps))
//                    .success {
//                        CLICK_BLE = true
//                        parserAppLoginData(it)
//                    }
//                    .error { _, msg ->
//
//                        val msg0 =
//                            if (msg.isNullOrEmpty()) _mActivity.getString(R.string.sign_in_failed) else msg
//                        onAppLoginFailed(msg0)
//                    }
//                    .failure {
//
//                        onAppLoginFailed(_mActivity.getString(R.string.sign_in_failed))
//                    }
//
//                    .build()
//                    .post()
//                onBackPressedSupport()
            }
        }
    }

    private fun onAppLoginFailed(msg0: String) {
        Toast.makeText(_mActivity, msg0, Toast.LENGTH_SHORT).show()
        onBackPressedSupport()
    }

    private fun parserAppLoginData(it: String?) {
        val userInfoWrapper = JSON.parseObject(it, UserInfoWrapper::class.java)
        UserInfoManager.userInfoManager.saveUserInfoWrapper(userInfoWrapper)
        MainActivity.entry(AppGlobals.getApplication())
    }

    private fun checkInfo(): Boolean {
        var flags = true

        val formViews = arrayOf(
            viewBinder.signUpPhone,
            viewBinder.signUpPassWord,
            viewBinder.signUpPayingPassWord,
            viewBinder.signUpInvitedCoding,
            viewBinder.signUpEMail,
        )

        for (item in formViews) {
            val validator = item.validator()
            if (validator?.isNotEmpty() == true) {
                Toast.makeText(_mActivity, validator, Toast.LENGTH_SHORT).show()
                flags = false
                break
            }
        }

//        if (signUpPhone.isNullOrEmpty()) {
//
//            flags = false
//
//        } else if (signUpPassWord.isNullOrEmpty()
//            || signUpPassWord.length < signUpPassWordMinLength
//        ) {
//
//            flags = false
//
//        } else if (signUpPayingPassWord.isNullOrEmpty()
//            || signUpPayingPassWord.length < payingPassWordMinLength
//        ) {
//
//            flags = false
//
//        } else if (signUpInvitedCoding.isNullOrEmpty()
//            || signUpInvitedCoding.length < invitedCodMinLength
//        ) {
//
//            flags = false
//
//        } else if (signUpEmail.isNullOrEmpty()) {
//
//            flags = false
//
//        }

        return flags
    }

    private fun registerAccount(verificationViewBean: VerificationViewBean) {
        val maps = mapOf(

            "hashCode" to verificationViewBean.requestTime,

            "account" to signUpPhone,

            "email" to signUpEmail,

            "password" to signUpPassWord,

            "payPasswd" to signUpPayingPassWord,

            "invitedCode" to signUpInvitedCoding,

            "token" to verificationViewBean.token
        )
        RestClient.builder()
            .url(R.string.SignUp)
            .raw(JSON.toJSONString(maps))
            .success {
                CLICK_BLE = true
                parserSignUpData(it)
            }
            .error { _, msg ->
                CLICK_BLE = true
                onSignUpFailed(msg)
            }
            .failure {
                CLICK_BLE = true
                onSignUpFailed(_mActivity.getString(R.string.sign_up_failed_22))
            }

            .build()
            .post()
    }

    private fun onSignUpFailed(msg: String) {

        Toast.makeText(_mActivity, msg, Toast.LENGTH_SHORT).show()
    }

    private fun parserSignUpData(it: String?) {
        Toast.makeText(_mActivity, "注册成功", Toast.LENGTH_SHORT).show()
//        onBackPressedSupport()
        signPageListener?.intoSignIn()
    }

    override fun afterTextChanged(s: Editable?, viewId: Int) {
        when (viewId) {
            R.id.sign_up_phone -> {
                //手机
                signUpPhone = s?.toString() ?: ""
            }
            R.id.sign_up_passWord -> {
                //登录密码
                signUpPassWord = s?.toString() ?: ""
            }
            R.id.sign_up_paying_passWord -> {
                //支付密码
                signUpPayingPassWord = s?.toString() ?: ""
            }
            R.id.sign_up_invited_coding -> {
                //邀请码
                signUpInvitedCoding = s?.toString() ?: ""
            }
            R.id.sign_up_e_mail -> {
                //邮箱
                signUpEmail = s?.toString() ?: ""
            }
        }
    }
}